﻿#region The MIT License (MIT)
// The MIT License (MIT)
// Copyright (c) 2010 - 2013 Sovacode LLC
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions
// of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
// BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Linq.Expressions;
using Sovacode.RubiksCube.Common.Base;
using Sovacode.RubiksCube.Common.Text;

namespace Sovacode.RubiksCube.Common.Managers.Validation
{
    /// <summary>
    /// Validation manager for objects
    /// </summary>
    internal sealed class ValidationManager : Manager<ValidationRule>, IValidationManager
    {
        #region Add Validation

        /// <summary>
        /// Register Validation Rule
        /// </summary>
        /// <typeparam name="T">Type of Property to Validate</typeparam>
        /// <param name="property">Property <see cref="Expression{TDelegate}"/></param>
        /// <param name="validation">Validation Function <see cref="Func{TResult}"/></param>
        /// <param name="message">Message</param>
        public void RegisterRule<T>(Expression<Func<T>> property, Func<bool> validation, string message = "")
        {
            RegisterRule(property.ExtractName(), validation, message);
        }

        /// <summary>
        /// Register Validation Rule
        /// </summary>
        /// <param name="propertyName">Property Name</param>
        /// <param name="validation">Validation Function <see cref="Func{TResult}"/></param>
        /// <param name="message">Message</param>
        public void RegisterRule(string propertyName, Func<bool> validation, string message = "")
        {
            if (validation == null)
            {
                validation = () => false;
            }

            if (string.IsNullOrEmpty(message))
            {
                message = string.Format(CategorizedBy.ValidationManagerMessages.InvalidPropertyMessage, propertyName);
            }

            RegisterRule(propertyName, new ValidationRule {Message = message, Validate = validation});

        }

        /// <summary>
        /// Register Validation Rule
        /// </summary>
        /// <param name="propertyName">Property Name</param>
        /// <param name="validationRule">Validation Rule <see cref="ValidationRule"/></param>
        public void RegisterRule(string propertyName, ValidationRule validationRule)
        {
            if (string.IsNullOrEmpty(propertyName))
            {
                throw new ArgumentNullException("propertyName");
            }

            if (validationRule == null)
            {
                validationRule = new ValidationRule { Message =  string.Format(CategorizedBy.ValidationManagerMessages.ValidatorIsEmptyMessage, String.Intern(propertyName)), Validate = () => false };
            }

            if (Dictionary.ContainsKey(String.Intern(propertyName)))
            {
                validationRule.Message = string.Format(CategorizedBy.ValidationManagerMessages.DuplicateValidator, propertyName);
            }

            Dictionary[String.Intern(propertyName)] = validationRule;
        }

        #endregion

        #region Validate

        /// <summary>
        /// Validate
        /// </summary>
        /// <typeparam name="T">Type of property</typeparam>
        /// <param name="property">Property <see cref="Expression{TDelegate}"/></param>
        /// <returns>Empty string if property valid</returns>
        public string Validate<T>(Expression<Func<T>> property)
        {
            return Validate(property.ExtractName());
        }

        /// <summary>
        /// Validate
        /// </summary>
        /// <param name="propertyName">Property Name</param>
        /// <returns>Empty string if property valid</returns>
        public string Validate(string propertyName)
        {
            if (Dictionary.ContainsKey(propertyName))
            {
                return Dictionary[String.Intern(propertyName)].IsValid ? string.Empty : Dictionary[String.Intern(propertyName)].Message;
            }

            Dictionary[String.Intern(propertyName)] = ValidationRule.CreateInvalidValidationRule(String.Intern(propertyName));

            return Validate(propertyName);
        }

        #endregion

        #region Public Properties

        /// <summary>
        /// Gets or sets a value indicating whether the object is valid
        /// </summary>
        public bool IsValid
        {
            get { return Dictionary.Values.All(o => o != null && o.IsValid); }
        }

        /// <summary>
        /// <see cref="IManager.InvalidProperties"/>
        /// </summary>
        public override IReadOnlyList<string> InvalidProperties
        {
            get { return new ReadOnlyCollection<string>((from validationRule in Dictionary where validationRule.Value != null && validationRule.Value.IsBroken select validationRule.Key).ToList()); }
        }

        /// <summary>
        /// <see cref="IManager.ValidProperties"/>
        /// </summary>
        public override IReadOnlyList<string> ValidProperties
        {
            get { return new ReadOnlyCollection<string>((from validationRule in Dictionary where validationRule.Value != null && !validationRule.Value.IsBroken select validationRule.Key).ToList()); }
        }

        #endregion
    }
}